package com.xgit.iov.codegen.config;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.xgit.iov.codegen.entity.GenDatasource;
import com.xgit.iov.codegen.service.IGenDatasourceService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;

/**
 * @Author: william
 * @Date: 2020/2/16 13:50
 */
@Component
@AllArgsConstructor
public class RegisterDataSource implements CommandLineRunner {

    private final DataSource dataSource;

    private final DataSourceCreator dataSourceCreator;

    @Autowired
    private IGenDatasourceService genDatasourceService;

    @Override
    public void run(String... args) throws Exception {

        List<GenDatasource> datasourceList = genDatasourceService.selectAllList();
        if (CollUtil.isNotEmpty(datasourceList) && datasourceList.size() > 0){

            for (GenDatasource datasource : datasourceList){
                DataSourceProperty dataSourceProperty = new DataSourceProperty();
                dataSourceProperty.setPollName(datasource.getPollName());
                dataSourceProperty.setUrl(datasource.getUrl());
                dataSourceProperty.setDriverClassName(datasource.getDriverClassName());
                dataSourceProperty.setUsername(datasource.getUsername());
                dataSourceProperty.setPassword(datasource.getPassword());
                DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
                DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
                ds.addDataSource(datasource.getPollName(), dataSource);
            }

        }
    }
}
